<?php

class thumbnail {

	private $chartID;
	private $ownerID;
	private $thumbnailID;
	private $rawHTML;
	private $runCommand;
	private $userObj;
	private $chart;

	public function __construct(user &$userObj, $chartID){
		if($chartID == "" || is_int($chartID) == false) throw new PicBoardException("Invalid chartID provided");
				
		$this->chartID = $chartID;
		$this->ownerID = $userObj->getuID();
		$this->userObj = $userObj;
		
		$this->chart = chart::getChart($this->userObj, $this->chartID);
		
		// If its a public chart save to location 0
		if($this->chart['data']['chart']['groupID'] == "" && $this->chart['data']['chart']['ownerID'] == ""){
			$this->ownerID = 0;
		}
		
		$this->getThumbnailInformation();

		$this->runCommand =  SYS_LIBDIR . "wkhtmltoimage-i386 '" . SYS_TMPDIR . "IMG/{$this->thumbnailID}.html' '" . SYS_IMGSTORE . "thumbnails/{$this->ownerID}/{$this->thumbnailID}'";

	}
	
	private function getThumbnailInformation(){
		// Retrieve the thumbnail information from the database
		$dbCon = db::singleton();
		
		$res = $dbCon->oneRow("SELECT thumbnail FROM " . SYS_DB_DBNAME . ".chart WHERE chID='" . $dbCon->real_escape_string($this->chartID) . "';");			
		// Set the thumb
		if($res['thumbnail'] != ""){
			$this->thumbnailID = $res['thumbnail'];
		} else {
			$this->setThumbnailInformation();
		}
	}
	
	private function copyTo($newID){
		// Copy a thumbnail to another chart
		$newID = $this->setThumbnailInformation($newID);
	}

	private function setThumbnailInformation($differentID = 0){
		// Retrieve the thumbnail information from the database
		$dbCon = db::singleton();
		
		$id = ($differentID == 0) ? $this->chartID : $differentID;
		
		$thumbid = md5(time() . rand(0, 99999)) . ".jpg";
		
		$dbCon->single("UPDATE " . SYS_DB_DBNAME . ".chart SET thumbnail='{$thumbid}' WHERE chID='" . $dbCon->real_escape_string((int)$id) . "';");			

		// Set the thumb
		if($differentID == 0) {
			$this->thumbnailID = $thumbid;
		} else {
			return $thumbid;
		}
	}

	private function writeHTMLFile($data){
		$this->rawHTML = $data;
		file_put_contents(SYS_TMPDIR . "IMG/{$this->thumbnailID}.html", $data);
	}
	
	private function writeIMGFile(){
	
		if( file_exists(SYS_IMGSTORE . "thumbnails/" . $this->ownerID) == false ) mkdir(SYS_IMGSTORE . "thumbnails/" . $this->ownerID);
	
		$cmd = escapeshellcmd( $this->runCommand );
		exec($cmd);
		
		if(file_exists(SYS_TMPDIR . "IMG/{$this->thumbnailID}.html")) unlink(SYS_TMPDIR . "IMG/{$this->thumbnailID}.html");
	}	
	
	private function generatePage(){
	
		$permissions = chart::chartExistsAndModifiable($this->userObj, array("chartID" => $this->chartID));
		
		if($permissions['status'] != "success") throw new PicBoardException($permissions['reason']);
		
		
		$main = new template("global");
		
		require_once(SYS_CLASSDIR . "controller.interface.php");
		require_once(SYS_CLASSDIR . "controllers/cntrlprint.class.php");
	
		$printController = new cntrlprint($this->userObj, $this->chartID);
		
		// Add required JS files
		$dependencies = $printController->getDependencies();
		
		$dependencyString = "";
		
		if(count($dependencies['JavaScript']) == 0 && count($dependencies['CSS']) == 0 && count($dependencies['InlineJavaScript']) == 0){
			// No external files to include.
			$main->replace("extra-scripts", "");
		} else {
		
			if( isset($dependencies['JavaScript']) ? count($dependencies['JavaScript']) : '' > 0){
				// Javascript files.
				$jsTemplate = new template("fragment.includeJS");
				
				foreach($dependencies['JavaScript'] as $inc){
					$dependencyString .= $jsTemplate->replace("name", $inc)->get();
					// Reset template back to placeholder state so that we can use it again.
					$jsTemplate->reset();
				}
				
			}
			
			if( isset($dependencies['InlineJavaScript']) ? count($dependencies['InlineJavaScript']) : '' > 0){
				// Inline Javascript.
				$jsTemplate = new template("fragment.inlineJS");
				
				foreach($dependencies['InlineJavaScript'] as $inc){
					$dependencyString .= $jsTemplate->replace("data", $inc)->get();
					// Reset template back to placeholder state so that we can use it again.
					$jsTemplate->reset();
				}
				
			}
			
			if( isset($dependencies['CSS']) ? count($dependencies['CSS']) : '' > 0){
				// Javascript files.
				$CSSTemplate = new template("fragment.includeCSS");
				
				foreach($dependencies['CSS'] as $inc){
					
					$CSSTemplate->replace("name", $inc);
					
					//$CSSTemplate->replace("extraAttrs", ($inc == "print.css") ? "media=\"print\"" : "");
					$CSSTemplate->replace("extraAttrs", "");
					
					
					$dependencyString .= $CSSTemplate->get();
					
					// Reset template back to placeholder state so that we can use it again.
					$CSSTemplate->reset();
				}
				
			}
		
		}
		
		// Insert the dependencies into the page.
		$main->replace("extra-scripts", $dependencyString);
		
		// Make replacements based on page
		$main->replace("area", $printController->getArea() );	
		
		// Change URL's to absolutes.
		$main->replace("absolute-url", SYS_BASEURL);
		
		return $main->get();			
	}

	
	public function deleteThumbnail(user &$userObj, $chartID){
		$this->getThumbnailInformation($userObj, $chartID);
		
		if(file_exists(SYS_IMGSTORE . "thumbnails/{$this->ownerID}/{$this->thumbnailID}")) unlink(SYS_IMGSTORE . "thumbnails/{$this->ownerID}/{$this->thumbnailID}");
	}
	
	public function createThumbnail(){
		
		$this->writeHTMLFile( $this->generatePage() );
		$this->writeIMGFile();
	}

	
}

?>